package com.example.uploadtest.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {


    @Value("${server.port}")
    private Integer httpsPort;
    @Value("${baseUrl}")
    private String baseUrl;

    @PostMapping(value = "/img")
    public JSONObject fileUpload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            System.out.println("文件为空");
            return null;
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String path = new File("").getCanonicalPath();
        fileName = System.currentTimeMillis() + suffixName; // 新文件名
        File dest = new File(path+"/img/" + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state","SUCCESS");
        jsonObject.put("url",baseUrl+":"+httpsPort+"/"+fileName);
       // return baseUrl+":"+httpsPort+"/"+fileName;
        return jsonObject;
    }


}
